<script setup>
import { ref } from "vue";
import { getEmailCodeAPI, verifyEmailAPI, resetPasswordAPI } from '@/apis/user'
import { ElMessage } from "element-plus";

const form = ref({
  email: "",
  emailCode: "",
});

const next = async () => {
  const e = form.value.email;
  const c = form.value.emailCode;
  if (!e || !c) {
    ElMessage.error("请输入邮箱和验证码");
    return;
  }
  
  try {
    // 使用 await 来等待异步操作完成
    const verifyRes = await verifyEmailAPI({
      email: e,
      code: c
    });

    // 如果验证邮件成功，继续重置密码
    const resetRes = await resetPasswordAPI(e);
    
    // 显示确认框
    await ElMessageBox.confirm(resetRes.message);
    
    done();
  } catch (err) {
    ElMessage.error("验证码 错误");
    console.log(err);
  }
};

const sendEmailCode = async () => {
  if (!form.value.email) {
    ElMessage.error("请输入邮箱");
    return;
  }
  await getEmailCodeAPI({
    email: form.value.email
  }).then(res => {
    ElMessage.success(res.message);
  }).catch(err => {
    ElMessage.error("验证码发送失败");
    console.log(err);
  })
};

const rules = {
  email: [
    {
      required: true,
      message: "请输入邮箱",
      trigger: "blur",
    },
    {
      type: "email",
      message: "请输入正确的邮箱地址",
      trigger: ["blur", "change"],
    },
  ],
  emailCode: [
    {
      required: true,
      message: "请输入邮箱验证码",
      trigger: "blur",
    },
  ],
};
</script>


<template>
  <div class="forget-password">
    <h1>重置密码</h1>
    <el-form :model="form" :rules="rules">
      <el-form-item prop="email">
        <el-input v-model="form.email" placeholder="请输入邮箱" prop="email"></el-input>
      </el-form-item>
      <el-form-item prop="emailCode">
        <el-input v-model="form.emailCode" placeholder="请输入邮箱验证码" style="margin-top: 1rem" prop="emailCode">
          <template #append>
            <el-button @click="sendEmailCode">发送验证码</el-button>
          </template>
        </el-input>
      </el-form-item>

      <el-button type="primary" style="width: 100%; margin-top: 1rem" @click="next">下一步</el-button>
    </el-form>
  </div>
</template>

<style lang="scss" scoped>
.forget-password {
  width: 100%;
  height: 50vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;

  h1 {
    font-size: 2rem;
    font-weight: bold;
    margin-bottom: 1rem;
  }
}
</style>